package zsc.liangyi.blog.web.client;

import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import zsc.liangyi.blog.model.ResponseData.ResponseData;
import zsc.liangyi.blog.model.domain.Comment;
import zsc.liangyi.blog.service.CommentService;
import zsc.liangyi.blog.utils.MyUtils;
import zsc.liangyi.blog.utils.UserUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Controller
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    private CommentService commentService;

    //发表评论
    @PostMapping("/publish")
    @ResponseBody
    public ResponseData publishComment(Model model,
                                       HttpServletRequest request,
                                       @RequestParam Integer aid,
                                       @RequestParam String text){
        //去除js脚本
        text= MyUtils.cleanXSS(text);
        text= EmojiParser.parseToAliases(text);//把emoji表情转为String

        //封装评论信息
        log.info("评论："+text);
        Comment comment=new Comment();
        comment.setArticleId(aid);
        comment.setIp(request.getRemoteAddr());//获取设置ip

        //获取当前登录用户，使用security
        if(!SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser")){
            log.info("当前登录："+SecurityContextHolder.getContext().getAuthentication());
            //如果当前是登录用户
            UserDetails user=(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            comment.setAuthor(user.getUsername());
        }else{
            //如果当前是游客
            comment.setAuthor("游客");
        }
        comment.setCreated(new Date());
        comment.setContent(text);

        try{
            commentService.pushComment(comment);
            log.info("评论详情："+comment);
            return ResponseData.ok();
        }catch (Exception e){
            log.error("发布评论失败：文章id："+aid+" ;错误"+e.getMessage());
            return ResponseData.fail();
        }

    }

}

